/**
 * @作者:黎谢之
 * @创建时间：2021/7/7
 * @修改时间：2021/7/13
 */
package com.example.senior_bug.Service;

import com.example.senior_bug.EntityClass.*;
import com.example.senior_bug.Repository.*;
import com.example.senior_bug.ToolClass.Result;
import com.example.senior_bug.enm.MsgId;
import com.example.senior_bug.utils.ImageFileUtils;
import com.example.senior_bug.utils.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@Service
public class BusinessService {
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private ChannelRepository channelRepository;
    @Autowired
    private CategoryRepository categoryRepository;
    @Autowired
    private BusinessRepository businessRepository;
    @Autowired
    private GoodRepository goodRepository;
    @Autowired
    private BrandRepository brandRepository;
    @Autowired
    private SKURepository skuRepository;
    @Autowired
    private SKUSpecificationOptionRepository skuSpecificationOptionRepository;
    @Autowired
    private SKUImageRepository skuImageRepository;
    @Autowired
    private SKUSpecificationImageRepository skuSpecificationImageRepository;

    /*注册并传图片
     * 7.15创建
     * 7.23修改
     * */
    public Result RegisterWithFaceImage(MultipartFile file, Business business) {
        //判断是否重复店铺名
        if (businessRepository.existsByStoreName(business.getStoreName())) {
            return ResultUtils.error(MsgId.STORENAME_HAVE_BEEN_REGISTER);
        }

        //判断是否重复注册身份证
        if (businessRepository.existsByIdentityNum(business.getIdentityNum())) {
            return ResultUtils.error(MsgId.IDENTITYNUM_HAVE_BEEN_REGISTER);
        }

        //判断是否重复注册手机号
        if ((business.getPhoneNum() != null) && businessRepository.existsByPhoneNum(business.getPhoneNum())) {
            return ResultUtils.error(MsgId.PHONENUM_HAVE_BEEN_REGISTER);
        }

        //判断是否重复注册邮箱
        if ((business.getEmail() != null) && businessRepository.existsByEmail(business.getEmail())) {
            return ResultUtils.error(MsgId.PHONENUM_HAVE_BEEN_REGISTER);
        }

        business.setUuid(UUID.randomUUID().toString().trim().replace("-", ""));//生成UUID

        Result result = ImageFileUtils.ModifyOrAddImage(file);//获取图片Url

        //处理图片文件异常
        switch (result.getCode()) {
            case 23:
                return ResultUtils.error(MsgId.FILE_IS_NULL);
            case 24:
                return ResultUtils.error(MsgId.FILE_TOO_LARGE);
            case 25:
                return ResultUtils.error(MsgId.EXTENSION_IS_INCORRECT);
            case 26:
                return ResultUtils.error(MsgId.FILE_EXCEPTION);
            default:
                break;
        }

        //复制头像图片Url
        String url = result.getDate().toString();
        business.setFaceUrl(url);

        //保存
        Business business1 = businessRepository.saveAndFlush(business);

        if (businessRepository.existsById(business1.getId())) {
            return ResultUtils.success(true);
        } else {
            return ResultUtils.error(MsgId.REGISTER_FAILED);
        }
    }

    /*测试函数
     * */
    public Result GetAll() {
        return ResultUtils.success(businessRepository.findAll());
    }

    /*商家首页通过传入店铺获取商家对象进而获取商家发布的所有商品
     * 1.店铺名字(StoreName)
     * 7.13增加了商家登录后原Name变为StoreName
     * */
    public Result GetBusinessSkusByStoreName(String StoreName) {
        //先判断商家是否存在
        if (businessRepository.existsByStoreName(StoreName)) {
            List<SKU> skus = new ArrayList<>();
            for (SKU item :
                    skuRepository.findAll()) {
                //只存储商家Id符合条件的商品
                if (businessRepository.findById(item.getBusinessId()).getStoreName().equals(StoreName)) {
                    Brand brand = brandRepository.findById(goodRepository.findById(item.getGoodId()).getBrandId());
                    //为临时变量赋值
                    item.setCategoryName(channelRepository.findById
                            (categoryRepository.findById(brand.getCategoryId())
                                    .getChannelId()).getName() + "/" + categoryRepository.findById(brand.getCategoryId()).getName());
                    item.setBrandName(brand.getName());
                    skus.add(item);
                }
            }
            return ResultUtils.success(skus);
        } else {
            return ResultUtils.error(MsgId.BUSINESS_NOT_FOUND);
        }
    }

    /*商家修改商品
     * 1.SKU对象(sku)
     * */
    public Result ModifySku(SKU sku) {
        //先判断商品是否存在
        if (skuRepository.existsById(sku.getId())) {
            for (SKUSpecificationOption item :
                    sku.getSkuSpecificationOptions()) {
                //存储每一个配置
                item.setSkuId(sku.getId());
                skuSpecificationOptionRepository.saveAndFlush(item);
            }
            //在数据库找到对应商品
            SKU sku1 = skuRepository.findById(sku.getId());

            //修改商品信息
            List<SKUImage> skuImages = sku1.getSkuImages();
            List<SKUSpecificationImage> skuSpecificationImages = sku1.getSkuSpecificationImages();
            List<SKUSpecificationOption> skuSpecificationOptions = sku1.getSkuSpecificationOptions();

            sku1.setSkuSpecificationOptions(sku.getSkuSpecificationOptions());
            sku1.setSkuImages(sku.getSkuImages());
            sku1.setSkuSpecificationImages(sku.getSkuSpecificationImages());
            sku1.setName(sku.getName());
            sku1.setState(sku.getState());
            sku1.setSubTitle(sku.getSubTitle());
            sku1.setSpecificationName(sku.getSpecificationName());

            //保存修改
            skuRepository.saveAndFlush(sku1);

            //删除不需要的图片
            for (SKUImage item :
                    skuImages) {
                if (!sku1.getSkuImages().contains(item))
                    skuImageRepository.delete(item);
            }

            //删除不需要的图片
            for (SKUSpecificationImage item :
                    skuSpecificationImages) {
                if (!sku1.getSkuSpecificationImages().contains(item))
                    skuSpecificationImageRepository.delete(item);
            }

            //删除不需要的配置
            for (SKUSpecificationOption item :
                    skuSpecificationOptions) {
                if (!sku1.getSkuSpecificationOptions().contains(item))
                    skuSpecificationOptionRepository.delete(item);
            }

            if (goodRepository.findById(sku1.getGoodId()).getSkus().contains(sku1) &&
                    businessRepository.findById(sku1.getBusinessId()).getSkus().contains(sku1)) {
                return ResultUtils.success(sku1.getId());
            } else {
                return ResultUtils.error(MsgId.MODIFY_ERROR);
            }
        } else {
            return ResultUtils.error(MsgId.ANYSKU_NOT_FOUND);
        }
    }

    /*商家上架
     * 1.SKU对象(sku)
     * 7.13由于字段名改变需要重新写Repository和service中的部分方法
     * */
    public Result AddNewSku(SKU sku) {

        //找到需要改商品外键的类
        Good good = goodRepository.findById(sku.getGoodId());
        Business business = businessRepository.findByStoreName(sku.getStoreName());

        //赋值
        sku.setBusinessId(business.getId());

        for (SKUSpecificationOption item :
                sku.getSkuSpecificationOptions()) {
            skuSpecificationOptionRepository.saveAndFlush(item);
        }

        SKU sku1 = skuRepository.saveAndFlush(sku);

        for (SKUSpecificationOption item :
                sku1.getSkuSpecificationOptions()) {
            item.setSkuId(sku1.getId());
            skuSpecificationOptionRepository.saveAndFlush(item);
        }

        business.getSkus().add(sku1);
        businessRepository.saveAndFlush(business);
        good.getSkus().add(sku1);
        goodRepository.saveAndFlush(good);
        if (goodRepository.findById(sku1.getGoodId()).getSkus().contains(sku1) &&
                businessRepository.findById(sku1.getBusinessId()).getSkus().contains(sku1)) {
            return ResultUtils.success(sku1.getId());
        } else {
            return ResultUtils.error(MsgId.ADDNEWSKU_FAILED);
        }
    }

    /*商家上架商品时传的图片(存储图片函数，没实现多张存储，只能循环单张存储)
     *
     * */
    public Result UploadNewSkuImage(MultipartFile file, int skuId, int flag) {

        //获取存储图片的Url
        Result result = ImageFileUtils.ModifyOrAddImage(file);

        //检查是否存储报错
        switch (result.getCode()) {
            case 23:
                return ResultUtils.error(MsgId.FILE_IS_NULL);
            case 24:
                return ResultUtils.error(MsgId.FILE_TOO_LARGE);
            case 25:
                return ResultUtils.error(MsgId.EXTENSION_IS_INCORRECT);
            case 26:
                return ResultUtils.error(MsgId.FILE_EXCEPTION);
            default:
                break;
        }

        //找到商品
        SKU sku = skuRepository.findById(skuId);

        String url = result.getDate().toString();

        //根据flag判断是哪种类型的图片
        if (flag == 1) {
            SKUImage skuImage = new SKUImage();
            skuImage.setUrl(url);
            skuImage.setSkuId(skuId);

            SKUImage skuImage1 = skuImageRepository.saveAndFlush(skuImage);

            sku.getSkuImages().add(skuImage1);

            SKU sku1 = skuRepository.saveAndFlush(sku);
            if (sku1.getSkuImages().contains(skuImage1))
                return ResultUtils.success("How Yeah! URL:" + url);
            else
                return ResultUtils.error(MsgId.FILE_EXCEPTION);
        } else if (flag == 2) {
            SKUSpecificationImage skuSpecificationImage = new SKUSpecificationImage();
            skuSpecificationImage.setUrl(url);
            skuSpecificationImage.setSkuId(skuId);

            SKUSpecificationImage skuSpecificationImage1 = skuSpecificationImageRepository.saveAndFlush(skuSpecificationImage);

            sku.getSkuSpecificationImages().add(skuSpecificationImage1);

            SKU sku1 = skuRepository.saveAndFlush(sku);
            if (sku1.getSkuSpecificationImages().contains(skuSpecificationImage1))
                return ResultUtils.success("How Yeah! URL:" + url);
            else
                return ResultUtils.error(MsgId.FILE_EXCEPTION);
        } else {
            return ResultUtils.error(MsgId.FLAG_NULL);
        }
    }

    /*商家通过手机登录
     * 7.13检查无问题
     * */
    public Result LoginByPhoneNum(String PhoneNum, String Password) {
        //判断该手机是否注册
        if (businessRepository.existsByPhoneNum(PhoneNum)) {
            Business business = businessRepository.findByPhoneNum(PhoneNum);
            //判断密码是否正确
            if (business.getPassWord().equals(Password)) {
                return ResultUtils.success(business);
            } else {
                return ResultUtils.error(MsgId.PASSWORD_NOT_CORRECT);
            }
        } else {
            return ResultUtils.error(MsgId.PHONE_NOT_REGISTER);
        }
    }

    /*商家通过邮箱登录
     * 7.13检查无问题
     * */
    public Result LoginByEmail(String Email, String Password) {
        //判断邮箱是否注册
        if (businessRepository.existsByEmail(Email)) {
            Business business = businessRepository.findByEmail(Email);
            //判断密码是否正确
            if (business.getPassWord().equals(Password)) {
                return ResultUtils.success(business);
            } else {
                return ResultUtils.error(MsgId.PASSWORD_NOT_CORRECT);
            }
        } else {
            return ResultUtils.error(MsgId.EMAIL_NOT_REGISTER);
        }
    }



    /*商家店铺信息修改
     * 缺陷
     * */
    public Result ModifyTheInfo(Business business) {
        if (businessRepository.existsById(business.getId())) {
            Business business1 = businessRepository.findById(business.getId());

            if (business1.getStoreName() != business.getStoreName() && businessRepository.existsByStoreName(business.getStoreName())) {
                return ResultUtils.error(MsgId.STORENAME_HAVE_BEEN_REGISTER);
            }

            if (business1.getPhoneNum() != business.getPhoneNum() && businessRepository.existsByPhoneNum(business.getPhoneNum())) {
                return ResultUtils.error(MsgId.PHONENUM_HAVE_BEEN_REGISTER);
            }

            if (business1.getEmail() != business.getEmail() && businessRepository.existsByEmail(business.getEmail())) {
                return ResultUtils.error(MsgId.EMAIL_HAVE_BEEN_REGISTER);
            }

            if (business1.getIdentityNum() != business.getIdentityNum() && businessRepository.existsByIdentityNum(business.getIdentityNum())) {
                return ResultUtils.error(MsgId.IDENTITYNUM_HAVE_BEEN_REGISTER);
            }

            business1.setStoreName(business.getStoreName());
            business1.setName(business.getName());
            business1.setEmail(business.getEmail());
            business1.setPhoneNum(business.getPhoneNum());
            business1.setFaceUrl(business.getFaceUrl());

            businessRepository.saveAndFlush(business1);
            return ResultUtils.success();
        } else {
            return ResultUtils.error(MsgId.CUSTOMER_NOT_FOUND);
        }
    }

    /*商家端店铺信息页面查询
     * 缺陷
     * */
    public Result getById(int id) {
        if (businessRepository.existsById(id)) {
            return ResultUtils.success(businessRepository.findById(id));
        } else {
            return ResultUtils.error(MsgId.BUSINESS_NOT_FOUND);
        }
    }

    /*商家和用户交流
     * 7.23修改
     * */
    public Result getAllCustomer(int businessId) {
        //判断商家是否存在
        if (businessRepository.existsById(businessId)) {
            Business business = businessRepository.findById(businessId);
            List<Customer> customers = new ArrayList<>();
            //获取聊过的用户列表
            for (Customer item :
                    business.getCustomers()) {
                Customer customer = new Customer();
                //只为需要的信息赋值
                customer.setName(item.getName());
                customer.setUuid(item.getUuid());
                customer.setFaceUrl(item.getFaceUrl());
                customers.add(customer);
            }
            return ResultUtils.success(customers);
        } else {
            return ResultUtils.error(MsgId.BUSINESS_NOT_FOUND);
        }
    }

    /*商家与一个新的用户联系
     * 缺陷
     * */
    public Result CommunicateWithNewCustomer(int BusinessId, int CustomerId) {
        if (businessRepository.existsById(BusinessId)) {
            if (customerRepository.existsById(CustomerId)) {
                Business business = businessRepository.findById(BusinessId);
                Customer customer = customerRepository.findById(CustomerId);
                business.getCustomers().add(customer);
                customer.getBusinesses().add(business);

                Customer customer2 = customerRepository.saveAndFlush(customer);
                Business business2 = businessRepository.saveAndFlush(business);
                if (businessRepository.findById(BusinessId).getCustomers().contains(customer2) &&
                        customerRepository.findById(CustomerId).getBusinesses().contains(business2)) {
                    return ResultUtils.success(true);
                } else {
                    return ResultUtils.error(MsgId.ADD_COMMUNICATION_ERROR);
                }
            } else {
                return ResultUtils.error(MsgId.CUSTOMER_NOT_FOUND);
            }
        } else {
            return ResultUtils.error(MsgId.BUSINESS_NOT_FOUND);
        }
    }

    /*商家下架商品
     * 7.23修改
     * */
    public Result DownTheSKU(int SKUId) {
        //先查找该商品是否存在
        if (skuRepository.existsById(SKUId)) {
            SKU sku = skuRepository.findById(SKUId);
            //修改商品状态
            sku.setState("已下架");
            skuRepository.saveAndFlush(sku);
            return ResultUtils.success(true);
        } else {
            return ResultUtils.error(MsgId.ANYSKU_NOT_FOUND);
        }
    }
}
